<?php
class Tender_Join_FinalController extends Agitum_Controller_Action
{
	protected $_redirector = null;

	public function init() {
		$this->_redirector = $this->_helper->getHelper('Redirector');
	}

	public function indexAction()
	{
		$final = new Zend_Session_Namespace('final');

		$slot = new Agitum_Model_Cache_Slot_Tender($final->id);
		$tender = $slot->load();
		if ( !$tender ) {
			$tender = new Agitum_Model_Tender( array('id' => $final->id ) );
			if ( !$tender->find() ) {
				$this->_redirector->gotoUrl('/');
			}
			$slot->addTag(new Agitum_Model_Cache_Tag_Tender($final->id));
			$slot->save($tender);
		}
		
		$this->view->tender = $tender;
		$this->view->form = $this->_helper->formLoader('Info');
	}
	
	public function sendAction() 
	{
		$form = $this->_helper->formLoader('Info');
		if (!$form->isValid($this->_request->getPost()))
	    	return;

	    $sms = $form->getValue("sms");
		$email = $form->getValue("email");
		
		if ( !$sms && !$email ) {
			$this->_redirector->gotoUrl('/');
		}
		
		$user = Zend_Registry::get('Logged_User');
		
		$final = new Zend_Session_Namespace('final');
		$slot = new Agitum_Model_Cache_Slot_Tender($final->id);
		$tender = $slot->load();
		if ( !$tender ) {
			$tender = new Agitum_Model_Tender( array('id' => $final->id ) );
			if ( !$tender->find() ) {
				$this->_redirector->gotoUrl('/');
			}
			$slot->addTag(new Agitum_Model_Cache_Tag_Tender($final->id));
			$slot->save($tender);
		}
		
		if ( $sms ) 
		{
			$view = new Zend_View();
			$view->setScriptPath(APPLICATION_PATH .'/views/sms');
			
			$view->tender_id = $tender->id;
			
			$msg = $view->render('tender.id.phtml');
			
			$smsGate = Zend_Registry::get('Agitum_Sms_Gate');
			$smsGate->send(array(
				'phones' => array($user->phone), 
				'message' => $msg,
				'translit' => 1,
				'charset' => 'utf-8'
			));
		}
		
		if ( $email ) 
		{
			$view = new Zend_View();
			$view->setScriptPath(APPLICATION_PATH .'/views/email');
			
			$view->tender_id = $tender->id;
			$msg = $view->render('tender.id.phtml');
			
			$mail = new Zend_Mail('UTF-8');
			$mail->setHeaderEncoding(Zend_Mime::ENCODING_BASE64);
			$mail->setBodyText($msg);
			$mail->addTo($user->email, $user->firstname.' '.$user->lastname);
			$mail->setSubject('Ваш заказ №'.$tender->id);
			$mail->send();
		}
		
		$this->_redirector->gotoUrl('/');
	}
}